<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        * {
            margin: 0;
            padding: 0;
        }

        div {
            width: 300px;
            height: 300px;
            background: url(./mylove.jpg);
            border: 3px solid red;
            
            position: fixed;
            top: 0;
            left: 0;
        }
    </style>
</head>

<body>
    <div></div>
    <script>
        /* 
            1. 获取盒子
            2. 点击盒子,鼠标按下 => 鼠标按下事件
                拖着移动 => 鼠标移动事件
            3. 鼠标抬起,就停止移动
        */
        // 获取盒子
        var box = document.querySelector("div")
        // 点击盒子,鼠标按下 => 鼠标按下事件
        box.onmousedown = function (e) {
            e = e || window.event;
            //获取鼠标移动之前的坐标
            var startX = e.offsetX
            var startY = e.offsetY;
            //鼠标按下,然后就拖拽
            document.onmousemove = function (e){
                e = e || window.event
                //获取鼠标移动之前的坐标
                var endX = e.clientX
                var endY = e.clientY

                //计算盒子应该要移动位置
                box.style.left = endX - startX + "px"
                box.style.top = endY - startY + "px"
            }
        }

        //鼠标抬起,就停止移动
        //
        document.onmouseup = function(){
            //解除事件绑定
            document.onmousemove = null;
        }
    </script>
</body>

</html>